<template>
  <div class="page-container">
    <el-row :gutter="24" class="main-layout-row">
      <el-col :span="7">
        <div class="steps-guide-wrapper">
          <div class="header">
            <el-icon><Guide /></el-icon>
            <span>分析步骤</span>
          </div>
          <div class="steps-list">
            <div class="step-item" :class="{ 'is-active': activeStep === 1, 'is-finished': activeStep > 1 }">
              <div class="step-icon-wrapper">
                <el-icon><UploadFilled /></el-icon>
              </div>
              <div class="step-content">
                <div class="step-title">上传文档</div>
                <div class="step-description">拖拽或点击选择至少两份学生作业。</div>
              </div>
            </div>
            <div class="step-item" :class="{ 'is-active': activeStep === 2, 'is-finished': activeStep > 2 }">
              <div class="step-icon-wrapper">
                <el-icon><MagicStick /></el-icon>
              </div>
              <div class="step-content">
                <div class="step-title">AI智能分析</div>
                <div class="step-description">启动分析引擎，AI进行深度逻辑与内容比对。</div>
              </div>
            </div>
            <div class="step-item" :class="{ 'is-active': activeStep === 3 }">
              <div class="step-icon-wrapper">
                <el-icon><DocumentChecked /></el-icon>
              </div>
              <div class="step-content">
                <div class="step-title">查看报告</div>
                <div class="step-description">查看详细的相似度报告和AI判决依据。</div>
              </div>
            </div>
          </div>
        </div>
      </el-col>

      <el-col :span="17">
        <el-card shadow="always" class="plagiarism-check-container">
          <template #header>
            <div class="card-header">
              <el-icon><CopyDocument /></el-icon>
              <span>学术诚信分析中心</span>
            </div>
          </template>

          <div v-if="!analysisCompleted" class="upload-section">
            <div v-if="isLoading" class="loading-overlay">
              <div class="ai-thinking-animation">
                <div></div><div></div><div></div><div></div><div></div>
                <div></div><div></div><div></div><div></div><div></div>
              </div>
              <div class="loading-text">AI引擎正在进行深度语义与逻辑分析，请稍候...</div>
            </div>
            
            <div :style="{ visibility: isLoading ? 'hidden' : 'visible' }" class="upload-content">
              <el-upload
                ref="uploadRef"
                drag
                multiple
                :auto-upload="false"
                :on-change="handleFileChange"
                :show-file-list="false"
                action="#"
                class="main-uploader"
              >
                <div class="uploader-icon-wrapper">
                  <el-icon :size="60"><UploadFilled /></el-icon>
                </div>
                <div class="el-upload__text">
                  将多份学生作业拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    为保证分析准确性，请至少上传2份 .doc 或 .docx 文件
                  </div>
                </template>
              </el-upload>
              
              <div v-if="fileList.length > 0" class="file-list-preview">
                <el-scrollbar max-height="180px">
                  <transition-group name="list" tag="div" class="file-list-grid">
                    <div v-for="file in fileList" :key="file.uid" class="file-item">
                      <el-icon class="file-icon"><Document /></el-icon>
                      <span class="file-name">{{ file.name }}</span>
                      <el-icon class="delete-icon" @click.stop="handleRemove(file)"><Delete /></el-icon>
                    </div>
                  </transition-group>
                </el-scrollbar>
              </div>

              <div class="action-bar">
                <el-button
                  type="primary"
                  size="large"
                  @click="startAnalysis"
                  :disabled="fileList.length < 2"
                  round
                  class="start-analysis-btn"
                >
                  <el-icon><DataAnalysis /></el-icon>
                  开始智能比对
                </el-button>
              </div>
            </div>
          </div>

          <div v-else class="results-section">
            <el-page-header @back="resetView">
              <template #content>
                  <span class="text-large font-600 mr-3"> 相似度分析报告 </span>
              </template>
            </el-page-header>
            <el-alert
              title="报告解读"
              type="info"
              description="本报告基于AI逻辑推理，分数越高代表两份文稿存在内容抄袭的可能性越大。分数高低仅为参考，最终结论请您结合“判决依据”进行人工判断。"
              show-icon
              :closable="false"
              style="margin-top: 20px;"
            />
            <el-table :data="report" stripe style="width: 100%; margin-top: 20px;">
              <el-table-column label="文稿 A" prop="fileA" />
              <el-table-column label="文稿 B" prop="fileB" />
              <el-table-column label="整体相似度" prop="overallScore" align="center" width="200">
                <template #default="scope">
                  <el-progress 
                    :percentage="parseFloat((scope.row.overallScore * 100).toFixed(2))"
                    :color="getSimilarityColor(scope.row.overallScore)"
                    :stroke-width="10"
                    striped
                    striped-flow
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                  <template #default="scope">
                      <el-button type="primary" link @click="handleViewDetails(scope.row)">
                          <el-icon><View /></el-icon>
                          查看详情
                      </el-button>
                  </template>
              </el-table-column>
            </el-table>
            <el-empty v-if="report.length === 0" description="未生成任何比对报告" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>

  <el-dialog v-model="detailsVisible" title="相似度比对详情" width="60%" top="5vh">
      <div v-if="selectedRow" class="details-dialog-content">
          <el-descriptions :column="2" border>
              <el-descriptions-item label-class-name="detail-label" label="文稿 A">{{ selectedRow.fileA }}</el-descriptions-item>
              <el-descriptions-item label-class-name="detail-label" label="文稿 B">{{ selectedRow.fileB }}</el-descriptions-item>
              <el-descriptions-item label-class-name="detail-label" label="整体相似度" :span="2">
                  <el-tag :type="getSimilarityTagType(selectedRow.overallScore)" size="large">
                      {{ (selectedRow.overallScore * 100).toFixed(2) }}%
                  </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label-class-name="detail-label" label="AI总体结论" :span="2">
                 <div style="white-space: pre-wrap;">{{ selectedRow.justification }}</div>
              </el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left">
            <el-icon><Tickets /></el-icon> 详细比对清单
          </el-divider>

          <el-scrollbar max-height="40vh">
              <div v-if="selectedRow.similarityDetails && selectedRow.similarityDetails.length > 0">
                  <el-card 
                      v-for="(detail, index) in selectedRow.similarityDetails" 
                      :key="index" 
                      class="detail-card"
                      shadow="never"
                  >
                      <template #header>
                          <div class="detail-card-header">
                              <span><el-icon><ScaleToOriginal /></el-icon> 相似句对 {{ index + 1 }}</span>
                              <el-tag effect="dark" :color="getSimilarityColor(detail.similarity)">
                                  相似度: {{ (detail.similarity * 100).toFixed(2) }}%
                              </el-tag>
                          </div>
                      </template>
                      <div class="sentence-pair">
                          <p><strong>文稿 A:</strong> {{ detail.sentenceFromA }}</p>
                          <p><strong>文稿 B:</strong> {{ detail.sentenceFromB }}</p>
                      </div>
                  </el-card>
              </div>
              <el-empty v-else description="AI未发现值得报告的具体相似句对。" />
          </el-scrollbar>
      </div>
       <template #footer>
        <span class="dialog-footer">
            <el-button @click="detailsVisible = false">关闭</el-button>
            <el-button type="primary" @click="detailsVisible = false">确定</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup>
// NO CHANGES TO SCRIPT LOGIC
import { ref, computed, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { 
    UploadFilled, 
    CopyDocument, 
    Document, 
    Delete, 
    DataAnalysis, 
    Guide, 
    MagicStick, 
    DocumentChecked,
    View,
    Tickets,
    ScaleToOriginal
} from '@element-plus/icons-vue';
import plagiarismService from '../../services/plagiarismService.js';

const uploadRef = ref();
const fileList = ref([]);
const isLoading = ref(false);
const report = ref([]);
const detailsVisible = ref(false);
const selectedRow = ref(null);
const analysisCompleted = ref(false);

const activeStep = computed(() => {
  if (analysisCompleted.value) return 3;
  if (isLoading.value) return 2;
  if (fileList.value.length > 0) return 2;
  return 1;
});

let isComponentUnmounted = false;
onUnmounted(() => {
  isComponentUnmounted = true;
});

const handleFileChange = (file, uploadedFiles) => {
  fileList.value = uploadedFiles;
};

const handleRemove = (fileToRemove) => {
  uploadRef.value.handleRemove(fileToRemove);
  fileList.value = fileList.value.filter(file => file.uid !== fileToRemove.uid);
};

const startAnalysis = async () => {
  if (fileList.value.length < 2) {
    ElMessage.warning('请至少上传两份文件进行比对。');
    return;
  }
  isLoading.value = true;
  try {
    const filesToUpload = fileList.value.map(f => f.raw);
    // Fake delay for demo purposes
    await new Promise(resolve => setTimeout(resolve, 3000)); 
    const result = await plagiarismService.analyzeSubmissions(filesToUpload);
    
    if (isComponentUnmounted) return; 

    report.value = result;
    analysisCompleted.value = true; 
    ElMessage.success('分析完成！所有比对结果已在下方表格呈现。');
  } catch (error) {
     if (isComponentUnmounted) return; 
     ElMessage.error(error.message || '分析失败，请稍后重试。');
  } finally {
     if (isComponentUnmounted) return;
    isLoading.value = false;
  }
};

const resetView = () => {
  report.value = [];
  fileList.value = [];
  analysisCompleted.value = false; 

  nextTick(() => {
    if (uploadRef.value) {
      uploadRef.value.clearFiles();
    }
  });
};

const handleViewDetails = (row) => {
  selectedRow.value = row;
  detailsVisible.value = true;
};

const getSimilarityColor = (similarity) => {
  if (similarity > 0.8) return '#F56C6C';
  if (similarity > 0.6) return '#E6A23C';
  if (similarity > 0.4) return '#409EFC';
  return '#67C23A';
};

const getSimilarityTagType = (similarity) => {
  if (similarity > 0.8) return 'danger';
  if (similarity > 0.6) return 'warning';
  if (similarity > 0.4) return 'primary';
  return 'success';
}
</script>

<style scoped>
/* --- 全局与布局 --- */
.page-container {
  background-color: #f0f2f5; /* 更柔和的背景色 */
  padding: 24px;
  min-height: calc(100vh - 100px);
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.main-layout-row {
  display: flex;
}
.main-layout-row .el-col {
  display: flex;
  flex-direction: column;
}

.el-card {
  border: 0;
  border-radius: 12px; /* 更大的圆角 */
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08); /* 更柔和的阴影 */
}
.el-card :deep(.el-card__body) {
  flex-grow: 1;
  padding: 24px;
}
.el-card :deep(.el-card__header) {
  border-bottom: 1px solid #e8eaec;
}

.card-header { 
  font-weight: 600;
  display: flex; 
  align-items: center; 
  gap: 10px; /* 增大了间距 */
  font-size: 1.2rem; /* 增大了字号 */
  color: #1f2d3d;
}

/* --- 左侧步骤指引 (全新设计) --- */
.steps-guide-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  height: 100%;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}
.steps-guide-wrapper .header {
  font-size: 1.2rem;
  font-weight: 600;
  color: #1f2d3d;
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 30px;
}
.steps-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.step-item {
  display: flex;
  align-items: center;
  padding: 18px;
  border-radius: 10px;
  border: 1px solid #e8eaec;
  transition: all 0.3s ease;
  background-color: #fafafa;
}
.step-item.is-active {
  border-color: var(--el-color-primary-light-3);
  background-color: var(--el-color-primary-light-9);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}
.step-item.is-finished .step-icon-wrapper {
  background-color: var(--el-color-success);
}
.step-icon-wrapper {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #dcdfe6;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  transition: background-color 0.3s ease;
}
.step-item.is-active .step-icon-wrapper {
  background-color: var(--el-color-primary);
}
.step-content {
  margin-left: 16px;
}
.step-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #303133;
}
.step-description {
  font-size: 0.9rem;
  color: #909399;
  margin-top: 4px;
}

/* --- 右侧主内容区 --- */
.upload-section {
  position: relative;
  text-align: center;
  height: 100%;
}
.upload-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

/* --- 上传组件 (全新设计) --- */
.main-uploader {
  width: 100%;
}
.main-uploader :deep(.el-upload-dragger) {
  padding: 40px;
  border: 2px dashed #dcdfe6;
  border-radius: 10px;
  transition: all 0.3s ease;
  background-color: #f9fafb;
}
.main-uploader :deep(.el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
  background-color: #f4f8ff;
}
.uploader-icon-wrapper {
  color: var(--el-color-primary);
  margin-bottom: 16px;
  animation: float 3s ease-in-out infinite;
}
@keyframes float {
	0% { transform: translateY(0px); }
	50% { transform: translateY(-10px); }
	100% { transform: translateY(0px); }
}
.el-upload__text {
  font-size: 1.1rem;
  color: #606266;
}
.el-upload__text em {
  color: var(--el-color-primary);
  font-weight: bold;
}
.el-upload__tip {
  margin-top: 10px;
  font-size: 0.9rem;
  color: #909399;
}

/* --- 高级加载动画 --- */
.loading-overlay {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  background-color: rgba(255, 255, 255, 0.95);
  z-index: 10;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 30px;
  transition: opacity 0.3s ease;
}
.loading-text {
  font-size: 1.2rem;
  font-weight: 500;
  color: var(--el-color-primary);
}
.ai-thinking-animation {
  width: 80px;
  height: 80px;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-template-rows: repeat(5, 1fr);
  gap: 5px;
}
.ai-thinking-animation div {
  background: var(--el-color-primary-light-5);
  border-radius: 3px;
  animation: ai-pulse 1.5s infinite ease-in-out;
}
@keyframes ai-pulse {
  0%, 100% { transform: scale(0.5); opacity: 0.5; }
  50% { transform: scale(1.0); opacity: 1; }
}
/* 制造动画延迟效果 */
.ai-thinking-animation div:nth-child(1) { animation-delay: 0.1s; }
.ai-thinking-animation div:nth-child(2) { animation-delay: 0.2s; }
.ai-thinking-animation div:nth-child(3) { animation-delay: 0.3s; }
.ai-thinking-animation div:nth-child(4) { animation-delay: 0.4s; }
.ai-thinking-animation div:nth-child(5) { animation-delay: 0.5s; }
.ai-thinking-animation div:nth-child(6) { animation-delay: 0.2s; }
.ai-thinking-animation div:nth-child(7) { animation-delay: 0.3s; }
.ai-thinking-animation div:nth-child(8) { animation-delay: 0.4s; }
.ai-thinking-animation div:nth-child(9) { animation-delay: 0.5s; }
.ai-thinking-animation div:nth-child(10) { animation-delay: 0.6s; }


/* --- 文件列表 (全新设计) --- */
.file-list-preview {
  width: 90%;
  margin: 25px auto;
}
.file-list-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
}
.file-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 15px;
  border-radius: 20px; /* 胶囊形状 */
  background-color: #f0f7ff;
  border: 1px solid var(--el-color-primary-light-7);
  transition: all 0.3s ease;
}
.file-item:hover {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}
.file-icon {
  color: var(--el-color-primary);
  font-size: 1.1rem;
}
.file-name { 
  font-size: 0.9rem;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex-grow: 1;
}
.delete-icon {
  color: #909399;
  cursor: pointer;
  margin-left: auto;
  font-size: 1rem;
  transition: color 0.2s ease;
}
.delete-icon:hover {
  color: var(--el-color-danger);
}

/* --- 操作按钮 (全新设计) --- */
.action-bar { 
    margin-top: 20px; 
}
.start-analysis-btn {
  padding: 18px 35px;
  font-size: 1.1rem;
  font-weight: 500;
  background: linear-gradient(45deg, var(--el-color-primary), #79bbff);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3);
}
.start-analysis-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.4);
}
.start-analysis-btn.is-disabled {
  background: #c8c9cc;
  box-shadow: none;
  transform: none;
}
.start-analysis-btn .el-icon {
  margin-right: 8px;
  font-size: 1.2em;
}

/* --- 结果与动画 --- */
.results-section { animation: fadeInUp 0.5s ease; }
@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}
.list-enter-active, .list-leave-active { transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1); }
.list-enter-from, .list-leave-to { opacity: 0; transform: scale(0.5) translateY(20px); }


/* --- 弹窗样式优化 --- */
.details-dialog-content {
    background-color: #f9fafb;
    padding: 24px;
    border-radius: 8px;
}
.detail-card {
    margin-bottom: 15px;
    border: 1px solid #e5e7eb;
    background-color: #ffffff;
    border-radius: 8px;
}
.detail-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
}
.detail-card-header span {
    display: flex;
    align-items: center;
    gap: 6px;
}
.sentence-pair p {
    margin: 10px 0;
    line-height: 1.7;
    color: #333;
    padding: 12px;
    border-radius: 6px;
}
.sentence-pair p:first-of-type {
    background-color: rgba(64, 158, 255, 0.08);
    border-left: 3px solid var(--el-color-primary-light-3);
}
.sentence-pair p:last-of-type {
     background-color: rgba(103, 194, 58, 0.08);
     border-left: 3px solid var(--el-color-success-light-3);
}
.sentence-pair p strong {
    color: var(--el-text-color-primary);
    font-weight: 600;
}
:global(.detail-label) {
    font-weight: 600 !important;
    width: 120px;
    color: var(--el-text-color-primary) !important;
    background-color: #fafcff !important;
}
.el-divider__text {
  font-weight: 500;
}
.el-divider .el-icon {
  margin-right: 6px;
}
</style>